//
//  TableViewController.m
//  Linkage
//
//  Created by LeeJay on 16/8/22.
//  Copyright © 2016年 LeeJay. All rights reserved.
//

#import "ClassificationGroupCell.h"
#import "ClassificationViewController.h"
#import <Masonry.h>
#import "JHMacros.h"

@interface ClassificationViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *categoryData;

@property (nonatomic, strong) UITableView *leftTableView;
@property (nonatomic, strong) UITableView *rightTableView;

@property(nonatomic,copy)ContentTableViewRegisteredCell registeredCell;
@property(nonatomic,assign)id <ClassificationDelegate> delegate;

@property(nonatomic,strong)NSIndexPath *selectIndexPath;
@end

@implementation ClassificationViewController
{
    NSInteger _selectIndex;
    BOOL _isScrollDown;
}

-(instancetype)initWithDelegate:(id<ClassificationDelegate>)delegate registeredCell:(ContentTableViewRegisteredCell)registeredCell
{
    self = [super init];
    if (self) {
        self.registeredCell = registeredCell;
        self.delegate = delegate;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.categoryTableCellHieght = 44;
    
    _selectIndex = 0;
    _isScrollDown = YES;

    [self.view addSubview:self.leftTableView];
    [self.view addSubview:self.rightTableView];

    [self.leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.width.equalTo(@100);
        make.height.equalTo(self.view);
        make.left.equalTo(self.view);
    }];
    
    [self.rightTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@64);
        make.left.equalTo(self.leftTableView.mas_right);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.leftTableView);
    }];
}

-(void)selcetObject:(id)object
{
    id<CategoryModel> reloadModel;
    for (id<CategoryModel> model in self.categoryData) {
        if ([model.dataArr containsObject:object]) {
            reloadModel = model;
            break;
        }
    }
    reloadModel.selectCount ++;
    NSInteger row = [self.categoryData indexOfObject:reloadModel];
    [self.leftTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:0]] withRowAnimation:(UITableViewRowAnimationNone)];
    [self.leftTableView selectRowAtIndexPath:self.selectIndexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
}

-(void)cancelSelcetObject:(id)object
{
    id<CategoryModel> reloadModel;
    for (id<CategoryModel> model in self.categoryData) {
        if ([model.dataArr containsObject:object]) {
            reloadModel = model;
            break;
        }
    }
    reloadModel.selectCount --;
    NSInteger row = [self.categoryData indexOfObject:reloadModel];
    [self.leftTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:0]] withRowAnimation:(UITableViewRowAnimationNone)];
    [self.leftTableView selectRowAtIndexPath:self.selectIndexPath animated:NO scrollPosition:UITableViewScrollPositionTop];

}


#pragma mark - Getters

- (NSMutableArray *)categoryData
{
    if (!_categoryData)
    {
        _categoryData = [NSMutableArray array];
    }
    return _categoryData;
}

-(void)addDataArr:(NSArray<CategoryModel> *)arr
{
    [self.categoryData removeAllObjects];
    [self.categoryData addObjectsFromArray:arr];
    [self.rightTableView reloadData];
    [self.leftTableView reloadData];
    
    self.selectIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.leftTableView selectRowAtIndexPath:self.selectIndexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
}

- (UITableView *)leftTableView
{
    if (!_leftTableView)
    {
        _leftTableView = [[UITableView alloc] init];
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
        _leftTableView.tableFooterView = [UIView new];
        _leftTableView.showsVerticalScrollIndicator = NO;
        _leftTableView.separatorColor = [UIColor clearColor];
        _leftTableView.bounces = NO;
        [_leftTableView registerNib:[UINib nibWithNibName:@"ClassificationGroupCell" bundle:nil] forCellReuseIdentifier:@"ClassificationGroupCell"];
    }
    return _leftTableView;
}

- (UITableView *)rightTableView
{
    if (!_rightTableView)
    {
        _rightTableView = [[UITableView alloc] init];
        _rightTableView.delegate = self;
        _rightTableView.dataSource = self;
        _rightTableView.rowHeight = 80;
        _rightTableView.showsVerticalScrollIndicator = NO;
        self.registeredCell(_rightTableView);
    }
    return _rightTableView;
}

#pragma mark - TableView DataSource Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_leftTableView == tableView)
    {
        return 1;
    }
    else
    {
        return self.categoryData.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_leftTableView == tableView)
    {
        return self.categoryData.count;
    }
    else
    {
        id<CategoryModel> model = self.categoryData[section];
        return model.dataArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_leftTableView == tableView)
    {
        id<CategoryModel> model = self.categoryData[indexPath.row];

        ClassificationGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ClassificationGroupCell" forIndexPath:indexPath];
        cell.title.text = model.categoryTitle;
        
        cell.selectedBackgroundView.backgroundColor = self.categorySelectBackgroundColor;
        cell.backgroundColor = self.categoryDefaultBackgroundColor;
        
        if (model.selectCount) {
            [cell.selectCount setHidden:NO];
            [cell.selectCount setTitle:[NSString stringWithFormat:@"%d",model.selectCount] forState:(UIControlStateNormal)];
        }else{
            [cell.selectCount setHidden:YES];
        }
        return cell;
    }
    else
    {
        
        id<CategoryModel> model = self.categoryData[indexPath.section];

        return [self.delegate classificationVC:self contentTableView:tableView cellForRowAtIndexPath:indexPath andModel:[model.dataArr objectAtIndex:indexPath.row]];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _leftTableView) {
        return self.categoryTableCellHieght;
    }else{
        
        if ([self.delegate respondsToSelector:@selector(classificationVC:contentTableView:heightForRowAtIndexPath:andModel:)]) {
            id<CategoryModel> model = self.categoryData[indexPath.section];
            
            return [self.delegate classificationVC:self contentTableView:tableView heightForRowAtIndexPath:indexPath andModel:[model.dataArr objectAtIndex:indexPath.row]];
        }else{
            return 44;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_rightTableView == tableView)
    {
        id<CategoryModel> model = self.categoryData[section];
        
        return [self.delegate classificationVC:self contentTableView:tableView heightForHeaderInSection:section andModel:model];
        
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (_rightTableView == tableView)
    {
        id<CategoryModel> model = self.categoryData[section];
        
        return [self.delegate classificationVC:self contentTableView:tableView viewForHeaderInSection:section andModel:model];
    }
    return nil;
}

// TableView分区标题即将展示
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(nonnull UIView *)view forSection:(NSInteger)section
{
    // 当前的tableView是RightTableView，RightTableView滚动的方向向上，RightTableView是用户拖拽而产生滚动的（（主要判断RightTableView用户拖拽而滚动的，还是点击LeftTableView而滚动的）
    if ((_rightTableView == tableView) && !_isScrollDown && _rightTableView.dragging)
    {
        [self selectRowAtIndexPath:section];
    }
}

// TableView分区标题展示结束
- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // 当前的tableView是RightTableView，RightTableView滚动的方向向下，RightTableView是用户拖拽而产生滚动的（（主要判断RightTableView用户拖拽而滚动的，还是点击LeftTableView而滚动的）
    if ((_rightTableView == tableView) && _isScrollDown && _rightTableView.dragging)
    {
        [self selectRowAtIndexPath:section + 1];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    if (_leftTableView == tableView)
    {
        _selectIndex = indexPath.row;
        self.selectIndexPath = indexPath;
        [_rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_selectIndex] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

// 当拖动右边TableView的时候，处理左边TableView
- (void)selectRowAtIndexPath:(NSInteger)index
{
    self.selectIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
    [_leftTableView selectRowAtIndexPath:self.selectIndexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
}

#pragma mark - UISrcollViewDelegate
// 标记一下RightTableView的滚动方向，是向上还是向下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    static CGFloat lastOffsetY = 0;

    UITableView *tableView = (UITableView *) scrollView;
    if (_rightTableView == tableView)
    {
        _isScrollDown = lastOffsetY < scrollView.contentOffset.y;
        lastOffsetY = scrollView.contentOffset.y;
    }
}

-(void)setCategoryDefaultBackgroundColor:(UIColor *)categoryDefaultBackgroundColor
{
    _categoryDefaultBackgroundColor = categoryDefaultBackgroundColor;
    [self.rightTableView reloadData];
}

-(void)setCategorySelectBackgroundColor:(UIColor *)categorySelectBackgroundColor
{
    _categorySelectBackgroundColor = categorySelectBackgroundColor;
    [self.rightTableView reloadData];
}

-(void)setCategoryTableCellWidth:(CGFloat)categoryTableCellWidth
{
    [self.leftTableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(categoryTableCellWidth));
    }];
}

-(void)setCategoryTableCellHieght:(CGFloat)categoryTableCellHieght
{
    _categoryTableCellHieght = categoryTableCellHieght;
}

@end
